<script name="CallbackBind" lang="ts" setup>
import { mobileRule, codeRule } from '@/utils/validate'
import { QQUserInfo } from '@/types/user.d.ts'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import useStore from '@/store'
import { useCountDown } from '@/utils/hooks'
import Message from '@/components/XtxMessage'
import { useField, useForm } from 'vee-validate'
const { user } = useStore()
const router = useRouter()
let openId = ''
const qqInfo = ref<QQUserInfo>({}) as QQUserInfo
if (QC.Login.check()) {
  QC.api('get_user_info').success((res: QQUserInfo) => {
    qqInfo.value = res.data
  })
  QC.Login.getMe((id) => {
    openId = id
  })
}

const { validate, resetForm } = useForm({
  initialValues: {
    mobile: '13012345765',
    code: '123456'
  },
  validationSchema: {
    mobile: mobileRule,
    code: codeRule
  }
})
const { value: mobile, errorMessage: mobileError } = useField<string>('mobile')
const { value: code, errorMessage: codeError } = useField<string>('code')
const { time, start } = useCountDown(60)
const send = async () => {
  if (time.value > 0) return
  await user.sendQQBindMsg(mobile.value)
  Message.success('发送验证')
  start()
}
const bind = async () => {
  const res = await validate()
  if (!res.valid) return
  // 如果校验，发送请求进行绑定
  // 如果校验，发送请求进行绑定
  await user.qqBindLogin(openId, mobile.value, code.value)
  Message.success('QQ绑定成功')
  router.push('/')
}
</script>
<template>
  <div class="xtx-form">
    <div class="user-info">
      <img
        :src="qqInfo.figureurl_qq"
        alt=""
      />
      <p>Hi，{{qqInfo.nickname}} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <input v-model="mobile" class="input" type="text" placeholder="绑定的手机号" />
      </div>
      <div v-if="mobileError" class="error">{{mobileError}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <input v-model="code" class="input" type="text" placeholder="短信验证码" />
        <span class="code" @click="send">{{time === 0 ? '发送验证码' : `${time}s后发送`}}</span>
      </div>
      <div v-if="codeError" class="error">{{codeError}}</div>
    </div>
    <a href="javascript:;" @click="bind" class="submit">立即绑定</a>
  </div>
</template>

<style scoped lang="less">
.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;
  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }
  p {
    padding-left: 10px;
  }
}
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
